package com.hksj.mqtt.connectlog;

import com.alibaba.fastjson.JSONObject;
import com.hksj.mqtt.annotation.MqttSubscription;
import com.hksj.mqtt.constant.MqttConstant;
import com.hksj.mqtt.listener.MqttListener;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

@MqttSubscription(topics = {MqttConstant.client_status})
public class ClientConnectLogListener implements MqttListener {

    @Autowired
    private ClientConnectLogDao clientConnectLogDao;

    @Override
    public void receive(String topic, MqttMessage mqttMessage) {
        try {
            ClientConnectLog log = JSONObject.parseObject(mqttMessage.toString(), ClientConnectLog.class);
            log.setType(log.getDisconnectedTime() != null ? 0 : 1);
            log.setCreateTime(new Date());
            if (log.getType() == 1){
                log.setConnectedTime(new Date());
            }else{
                log.setDisconnectedTime(new Date());
            }
            clientConnectLogDao.insert(log);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
